﻿using CaseManagerLibrary.Socket;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSDLib.Protocols
{
    public static class MessageParser
    {
        private static Dictionary<string, Type> MessageTypeSet = new Dictionary<string, Type>();

        public static MessageBase Parse(byte[] data)
        {
            return Parse(MessageBase.Decode(data));
        }

        public static MessageBase Parse(string text)
        {
            var obj = JObject.Parse(text);
            string name = obj["Name"].Value<string>();

            if (string.IsNullOrEmpty(name))
            {
                return null;
            }
            else
            {
                MessageBase message = null;
               
                try
                {
                    Type msgType = null;
                    string typeName = "PSDLib.Protocols." + name + "Message";

                    if (MessageTypeSet.ContainsKey(typeName))
                    {
                        msgType = MessageTypeSet[typeName];
                    }

                    if (msgType == null)
                    {
                        System.Reflection.Assembly assm = System.Reflection.Assembly.Load("PSDLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                        msgType = assm.GetType(typeName);
                      
                        MessageTypeSet.Add(typeName, msgType);
                    }

                    message = (MessageBase)JsonConvert.DeserializeObject(text, msgType);
                }
                catch (Exception ex)
                {
                    
                }

                return message;
            }
        }

       
    }
}
